define(['jquery', 'bootstrap', 'backend', 'template', 'table', 'form', 'moduleSet', 'dragsort'], function($, undefined, Backend, Template, Table, Form, undefined, undefined) {
    var Controller = {
        index: function() {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'formdesign/Form/index',
                    add_url: 'formdesign/Form/add',
                    edit_url: 'formdesign/Form/edit',
                    del_url: 'formdesign/Form/del',
                    multi_url: 'formdesign/Form/multi',
                    table: 'form'
                }
            });
            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                escape: false,
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('序号'), operate: false },
                        { field: 'form_name', title: __('表单名称'), align: 'center' },
                        { field: 'form_desc', title: __('表单描述'), align: 'center' },
                        { field: 'url', title: __('前台链接'), formatter: Controller.api.formatter.url },
                        { field: 'status', title: __('Status'), formatter: Table.api.formatter.status, searchList: { 'normal': __('Normal'), 'hidden': __('Hidden') }, style: 'min-width:100px;' },
                        {
                            field: 'button',
                            title: __('表单内容'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [{
                                    name: 'data',
                                    text: __('数据'),
                                    title: __('数据'),
                                    extend: 'data-area=\'["100%","100%"]\'',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    icon: 'fa fa-database',
                                    url: 'formdesign/foreign/index'
                                },
                                {
                                    name: 'design',
                                    text: __('设计'),
                                    title: __('设计'),
                                    extend: 'data-area=\'["100%","100%"]\'',
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    icon: 'fa fa-pencil-square-o',
                                    url: 'formdesign/form/drag'
                                },
                                {
                                    name: 'preview',
                                    text: __('预览'),
                                    title: __('预览'),
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    icon: 'fa fa-search',
                                    url: 'formdesign/form/preview'
                                }
                            ],
                            formatter: Table.api.formatter.buttons
                        },
                        { field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate }
                    ]
                ],
                search: false
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        drag: function() {
            require(['moduleSet', 'dragsort', 'plugins'], function(undefined, undefined, Plugins) {
                //阻止按键事件
                $('body', document).on('keyup', function(e) {
                    if (e.which === 27) {
                        return false;
                    }
                });
                /**
                 * 监听页面刷新或关闭事件
                 */
                $(window).on('beforeunload', function() {
                    return "您确定要离开吗？！";
                });
                Controller.api.plugins = Plugins;
                //初始化
                Controller.api.drapSort();
                $("#target").find('.form-group').each(function() {
                    Controller.api.createShade(this);
                });

                if ($('#layout').is(':checked')) {
                    $('form').addClass('form-horizontal');
                    $("ul.components label").addClass('control-label col-xs-12 col-sm-2');
                    $("#target label").addClass('control-label col-xs-12 col-sm-2')
                    $("div.html").addClass('col-sm-12');
                    $("div.plugins").addClass('col-xs-12 col-sm-8');
                    $('#layout').val('form-horizontal');
                }
                //新增控件事件
                Controller.api.addPlugins();
                $('#button_review').on('click', function() {
                    Controller.api.genSource();
                    var form_id = $('#form_id').val();
                    var content = $('#source').val();
                    var layout = $('#layout').val();
                    if (content.length > 1) {
                        Fast.api.open(
                            'formdesign/Form/tempview?layout=' + layout + '&form_id=' + form_id + '&design_content=' + encodeURIComponent(content),
                            '预览', {}
                        );
                    } else {
                        Toastr.warning('表单内容不能为空！');
                        return false;
                    }
                });
                $('#layout').on('change', function() {
                    $('form').toggleClass('form-horizontal');
                    $("ul.components label").toggleClass('control-label col-xs-12 col-sm-2');
                    $("#target label").toggleClass('control-label col-xs-12 col-sm-2')
                    $("div[data-type=html] div.html").toggleClass('col-sm-12');
                    $("div.plugins").toggleClass('col-xs-12 col-sm-8');
                    $(this).is(':checked') ? $(this).val('form-horizontal') : $(this).val('');
                });
                $('#tab_source').on('click', function() {
                    Controller.api.genSource();
                });

                $('#button_source').on('click', function() {
                    Controller.api.genSource();
                    var content = $('#source').val();
                    if (content.length > 1) {
                        Layer.open({
                            title: '源代码',
                            area: ['800px', '800px'],
                            content: '<xmp>' + content + '</xmp>'
                        });
                    } else {
                        Toastr.warning('表单内容不能为空！');
                        return false;
                    }
                });
                var isClick = true;
                $('#button_save').on('click', function(e) {
                    if (isClick) {
                        isClick = false;
                        var btn = $(this);
                        Controller.api.genSource();
                        btn.attr("disabled", true);
                        var form_id = $('#form_id').val();
                        var content = $('#source').val();
                        var layout = $('#layout').is(':checked') ? 'form-horizontal' : '';
                        if (content.length > 1) {
                            $.post('formdesign/form/drag', {
                                ids: form_id,
                                layout: layout,
                                design_content: content
                            }).complete(function(XMLHTTPRequest, result) {
                                var json = XMLHTTPRequest.responseJSON;
                                if (json.code) {
                                    Fast.api.success(json.msg, function() {
                                        $(window).off('beforeunload');
                                        location.reload();
                                    })
                                } else {
                                    Fast.api.error(json.msg,function() {
                                        btn.attr("disabled", false);
                                    });
                                    
                                }
                            });
                        } else {
                            Toastr.warning('表单内容不能为空！');
                            return false;
                        }
                        setTimeout(function() {
                            isClick = true;
                        }, 2000); //一秒内不能重复点击
                    }
                });
            });
            Controller.api.bindevent();
        },
        settings: function() {
            
        },
        tempview: function() {
            Controller.api.bindevent();
        },
        preview: function() {
            Controller.api.bindevent();
        },
        add: function() {
            Controller.api.bindevent();
        },
        edit: function() {
            Controller.api.bindevent();
        },
        api: {
            plugins: null,
            addPlugins: function() {
                $('ul.components li').click(function(e) {
                    var content = $(this).find('.content').html();
                    $('#target').append(content);
                    Controller.api.openSettingDlg($('div#target .form-group:last'), function(ret) {
                        if (ret) {
                            Controller.api.createShade($('div#target .form-group:last'));
                            Controller.api.genSource();
                            Controller.api.drapSort();
                        } else {
                            $('div#target .form-group:last').remove();
                        }
                    });
                });
            },
            drapSort: function() {
                $("#target").dragsort('destroy');
                $("#target").dragsort({
                    dragSelector: "div.form-group",
                    dragSelectorExclude: 'button',
                    dragBetween: true,
                    placeHolderTemplate: "",
                    dragEnd: function() {
                        Controller.api.genSource();
                    }
                });
            },
            genSource: function() {
                var $temptxt = $("<div>").html($("#target").html());
                $($temptxt).find('.form-group').attr('style', null);
                $($temptxt).find('.plugins').empty();
                $($temptxt).find('.panel-module-box').remove();
                $("#source").val($($temptxt).html().replace(/\s{2,}/g, "\n"));
            },
            getAttribute: function(plugins, type) {
                if (type === 'html') {
                    var html = $(plugins).find('div.html').html();
                    return 'html=' + encodeURIComponent(html);
                }
                var pattern = /data-(\w*)=\"([^\"\']*)\"/g;
                var str = $(plugins).find("div.options input[type='hidden']").prop("outerHTML");
                var temp;
                var data = [];
                var name, value;
                while (temp = pattern.exec(str)) {
                    name = temp[1];
                    value = temp[2] ? temp[2] : '';
                    data.push(name + '=' + value);
                }
                return data.join('&');
            },
            openSettingDlg: function(el, callback) {
                var self = $(el);
                var type = self.data('type');
                if (type && typeof(type) !== 'undefined' && type !== '') {
                    var title = type == "html" ? "自定义HTML" : self.find('label.plugins-label').text();
                    var attribute = Controller.api.getAttribute(self, type);
                    Layer.open({
                        type: 2,
                        title: title,
                        shadeClose: false,
                        shade: 0.8,
                        area: ['550px', '60%'],
                        content: '../../settings?type=' + type + '&' + attribute,
                        btn: ['保存', '关闭'],
                        success: function(layero, index){
                            var form=Layer.getChildFrame('form[role=form]', index);
                            Form.api.bindevent(form,null,null,function(){
                                Controller.api.plugins(type, index, self, function() {
                                    callback && typeof(callback) === 'function' && callback(true);
                                });
                                Layer.close(index);
                                return false
                            });
                        },
                        yes: function(index, layero) {
                            try {
                                var form=Layer.getChildFrame('form[role=form]', index);
                                // 获取表单中的提交按钮（在我的表单⾥第⼀个button按钮就是提交按钮，使⽤find⽅法寻找即可）
                                var submited = form.find('button[type="submit"]')[0];
                                // 触发点击事件，会对表单进⾏验证，验证成功则提交表单，失败则返回错误信息
                                submited.click();
                            } catch (e) {
                                alert('控件异常！');
                            }
                        },
                        btn2: function(index, layero) {
                            callback && typeof(callback) === 'function' && callback(false);
                            Layer.close(index);
                        },
                        cancel: function(index, layero) {
                            callback && typeof(callback) === 'function' && callback(false);
                            Layer.close(index);
                        }
                    });
                }
            },
            createShade: function(el) {
                $(el).moduleSet({
                    button: [{
                            text: '编辑',
                            callback: function(e) {
                                Controller.api.openSettingDlg($(el));
                            }
                        },
                        {
                            text: '删除',
                            callback: function(e) {
                                $(el).remove();
                                Controller.api.genSource();
                            }
                        }
                    ]
                });
            },
            formatter: {
                url: function(value, row, index) {
                    var ids = row['id'];
                    return '<div class="input-group input-group-sm" style="width:250px;margin:0 auto;"><input type="text" class="form-control input-sm" value="/index/formdesign/foreign/index/form_id/' + ids + '"><span class="input-group-btn input-group-sm"><a href="/index/formdesign/foreign/index/form_id/' + ids + '" target="_blank" class="btn btn-default btn-sm"><i class="fa fa-link"></i></a></span></div>';
                }
            },
            bindevent: function() {
                Form.api.bindevent("form[role=form]");
            }
        }
    };
    return Controller;
});